package com.andon.microcellsimulator.common.util;

import android.util.Base64;

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {

    /**
     * AES加密算法
     * @param content 明文字节流
     * @param key 密钥
     * @return 密文
     */
    public static byte[] aesEncrypt(byte[] content, String key) {
        if (content == null || key == null) return null;

        byte[] bytes = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
            bytes = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Base64.encode(bytes, Base64.NO_WRAP);
    }

    /**
     * AES解密算法
     * @param content 密文字节流
     * @param key 密钥
     * @return 明文
     */
    public static byte[] aesDecrypt(byte[] content, String key) {
        if (content == null || key == null) return null;

        byte[] bytes = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
            bytes = cipher.doFinal(Base64.decode(content, Base64.NO_WRAP));
        } catch (Exception e) {
            String str = new String(content);
            e.printStackTrace();
        }

        return bytes;
    }

    /**
     * 生成GUID
     * @return GUID
     */
    public static String getGUID() {

        UUID uuid = UUID.randomUUID();
        // 转换为小写并替换"-"
        return uuid.toString().toLowerCase().replaceAll("-", "");

    }

    /**
     * 生成16字节随机码
     * @return GUID
     */
    public static String getRandomString() {

        String res = getGUID();

        // 转换为小写并替换"-"
        return res.substring(0, 16);

    }

    /**
     * 生成不重复的数字(8位数int)
     * @return GUID
     */
    public static int getNotifyID() {

        String res = String.valueOf(System.currentTimeMillis());

        return Integer.parseInt(res.substring(res.length() - 8));

    }

}
